package com.siam.package_rider.service_impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.siam.package_common.constant.BasicResultCode;
import com.siam.package_common.constant.BusinessType;
import com.siam.package_common.constant.Quantity;
import com.siam.package_common.constant.RedisConstant;
import com.siam.package_common.exception.StoneCustomerException;
import com.siam.package_common.service.AliyunSms;
import com.siam.package_common.util.BaiduMapUtils;
import com.siam.package_common.util.DateUtilsExtend;
import com.siam.package_common.util.DateUtilsPlus;
import com.siam.package_common.util.RedisUtils;
import com.siam.package_order.entity.TravelingDistanceVo;
import com.siam.package_order.feign.CommonFeignApi;
import com.siam.package_order.feign.OrderFeignApi;
import com.siam.package_order.model.param.OrderParam;
import com.siam.package_rider.cache.RiderSessionManager;
import com.siam.package_rider.entity.TbDeliveryAreaConfig;
import com.siam.package_rider.entity.TbDeliveryOrder;
import com.siam.package_rider.entity.TbRider;
import com.siam.package_rider.entity.TbRiderLevel;
import com.siam.package_rider.enums.DeliveryOrderStatusEnum;
import com.siam.package_rider.mapper.TbDeliveryOrderMapper;
import com.siam.package_rider.mapper.TbRiderLevelMapper;
import com.siam.package_rider.model.param.TbDeliveryOrderParam;
import com.siam.package_rider.model.result.TbDeliveryOrderResult;
import com.siam.package_rider.service.TbDeliveryAreaConfigService;
import com.siam.package_rider.service.TbDeliveryOrderService;
import com.siam.package_rider.util.TokenUtil;
import com.siam.package_weixin_basic.service.WxNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.siam.package_common.constant.RedisConstant.*;

/**
 * ---------------------------
 * 配送订单表 (TbDeliveryOrderServiceImpl)         
 * ---------------------------
 * 作者：  高品
 * 时间：  2025-03-29 18:55:18
 * ---------------------------
 */
@Slf4j
@Service
public class TbDeliveryOrderServiceImpl extends ServiceImpl<TbDeliveryOrderMapper, TbDeliveryOrder> implements TbDeliveryOrderService {

	@Autowired
	private TbDeliveryOrderMapper tbDeliveryOrderMapper;

	@Autowired
	private TbRiderLevelMapper tbRiderLevelMapper;

	@Autowired
	private TbDeliveryAreaConfigService deliveryAreaConfigService;

	@Autowired
	private RedisTemplate<String,Object> redisTemplate;

	@Autowired
	private RiderSessionManager riderSessionManager;

	@Autowired
	private RedissonClient redissonClient;

	@Autowired
	private BaiduMapUtils baiduMapUtils;

	@Autowired
	private AliyunSms aliyunSms;

	@Autowired
	private WxNotifyService wxNotifyService;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private CommonFeignApi commonFeignApi;

	@Autowired
	private OrderFeignApi orderFeignApi;

	@Override
	public void insert(TbDeliveryOrderParam param) {
		TbDeliveryOrder deliveryOrder = new TbDeliveryOrder();
		BeanUtils.copyProperties(param, deliveryOrder);

		// 新增配送订单
		tbDeliveryOrderMapper.insert(deliveryOrder);

		// 记录配送订单出发地位置到Redis中
		Point merPoint = new Point(Convert.toDouble(deliveryOrder.getStartLng()), Convert.toDouble(deliveryOrder.getStartLat()));
		redisTemplate.opsForGeo().add(ORDER_START_ADDRESS_KEY, merPoint, deliveryOrder.getId().toString());
	}

	@Override
	public void delete(Long id) {
		tbDeliveryOrderMapper.deleteById(id);
	}

	@Override
	public void batchDelete(List<Long> idList) {
		tbDeliveryOrderMapper.deleteBatchIds(idList);
	}

	@Override
	public void update(TbDeliveryOrderParam param) {
		TbDeliveryOrder record = new TbDeliveryOrder();
		BeanUtils.copyProperties(param, record);
		tbDeliveryOrderMapper.updateById(record);
	}

	@Override
	public Page<TbDeliveryOrder> page(TbDeliveryOrderParam param) {
        Page<TbDeliveryOrder> page = tbDeliveryOrderMapper.page(new Page(param.getPageNo(), param.getPageSize()), param);
        return page;
	}

	@Override
	public TbDeliveryOrder findById(Long id) {
		return tbDeliveryOrderMapper.selectById(id);
	}

	public List<TbDeliveryOrder> queryByIdsAndStatus(List<Long> ids) {
		if(ObjectUtils.isEmpty(ids)) return Lists.newArrayList();
		LambdaQueryWrapper<TbDeliveryOrder> lambdaQueryWrapper = Wrappers.<TbDeliveryOrder>lambdaQuery()
				.in(TbDeliveryOrder::getId, ids).eq(TbDeliveryOrder::getStatus, DeliveryOrderStatusEnum.WAITING_FOR_ORDERS.getCode());
		return tbDeliveryOrderMapper.selectList(lambdaQueryWrapper);
	}

	public Page<TbDeliveryOrderResult> page(TbDeliveryOrderParam.DeliveryOrderPageRequest param) {
		try {
			// 获取骑手信息
			TbRider loginRider = riderSessionManager.getSession(TokenUtil.getToken());

			// 更新骑手位置到Redis
			Double riderLng = param.getRiderLng().doubleValue();
			Double riderLat = param.getRiderLat().doubleValue();
			Point point = new Point(riderLng, riderLat);
			redisTemplate.opsForGeo().add(RIDER_DIST_KEY, point, loginRider.getId().toString());

			// 获取全国配送区域配置
			// TODO - 按当前城市地区计算
			TbDeliveryAreaConfig nationalDeliveryAreaConfig = deliveryAreaConfigService.getById(BusinessType.DELIVERY_AREA_CONFIG_NATIONAL_ID);
			if(nationalDeliveryAreaConfig == null){
				throw new StoneCustomerException("全国配送区域配置获取失败");
			}

			Distance radius = new Distance(nationalDeliveryAreaConfig.getNearbyRidersDistanceLimit().doubleValue(), RedisGeoCommands.DistanceUnit.KILOMETERS);
			Circle circle = new Circle(point, radius);

			// 获取足够多的数据以支持分页
			RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
					.newGeoRadiusArgs()
					.includeDistance() // 包含距离信息
					.sortAscending() // 按距离升序排序
					.limit((param.getPageNo() + 1) * param.getPageSize()); // 获取足够多的数据

			GeoResults<RedisGeoCommands.GeoLocation<Object>> results = redisTemplate.opsForGeo()
					.radius(ORDER_START_ADDRESS_KEY, circle, args);

			// 计算总记录数
			Long totalCount = 0L;
			List<Long> ids = new ArrayList<>();
			if (results != null && CollectionUtil.isNotEmpty(results.getContent())) {
				// 排除拒绝的订单
				Map refuseMap = redisUtils.hasKey(RedisConstant.REFUSE_ORDER_KEY) ? JSON.parseObject((String) redisUtils.get(RedisConstant.REFUSE_ORDER_KEY), HashMap.class) : new HashMap();
				List<Long> orderIdList = refuseMap.containsKey(loginRider.getId()) ? (List) refuseMap.get(loginRider.getId()) : new ArrayList<>();

				List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> tempList = (List<GeoResult<RedisGeoCommands.GeoLocation<Object>>>) results.getContent().stream().filter(obj -> !orderIdList.contains(Convert.toLong(obj.getContent().getName()))).collect(Collectors.toList());

				totalCount = (long) tempList.size();

				// 在应用层实现分页
				ids = tempList.stream()
						.skip((param.getPageNo()-1) * param.getPageSize())
						.limit(param.getPageSize())
						.map(t -> Long.valueOf(t.getContent().getName().toString()))
						.collect(Collectors.toList());
			}

			List<TbDeliveryOrderResult> resultList = new ArrayList<>();
			if(CollectionUtil.isNotEmpty(ids)){
				// 从数据库获取订单详情
				List<TbDeliveryOrder> list = queryByIdsAndStatus(ids);
				list.sort(Comparator.comparing(TbDeliveryOrder::getCreateTime));

				for (TbDeliveryOrder deliveryOrder : list) {
					TbDeliveryOrderResult tbDeliveryOrderResult = new TbDeliveryOrderResult();
					BeanUtils.copyProperties(deliveryOrder, tbDeliveryOrderResult);
					resultList.add(tbDeliveryOrderResult);
				}
			}

			// 填充预计到店分钟等字段值
			resultList.forEach(result -> {
				setDistanceField(result, param.getRiderLng(), param.getRiderLat());
			});

			// 构建分页结果
			Page<TbDeliveryOrderResult> page = new Page<>();
			page.setRecords(resultList);
			page.setCurrent(param.getPageNo());
			page.setTotal(totalCount);
			page.setSize(param.getPageSize());

			return page;
		} catch (StoneCustomerException e) {
			throw e;
		} catch (Exception e) {
			log.error("Failed to get delivery orders page", e);
			return new Page<>();
		}
	}

	@Override
	public void grabOrder(TbDeliveryOrderParam.GrabOrderRequest request) {
		// 获取骑手信息
		String token = TokenUtil.getToken();
		TbRider rider = riderSessionManager.getSession(token);
		if(ObjectUtils.isEmpty(rider)){
			throw new StoneCustomerException("骑手信息获取失败");
		}

		// 查询出来订单信息
		TbDeliveryOrder dbDeliveryOrder = tbDeliveryOrderMapper.selectById(request.getId());
		if(ObjectUtils.isEmpty(dbDeliveryOrder)){
			throw new StoneCustomerException("订单不存在");
		}

		// 获取分布式锁
		RLock lock = redissonClient.getLock(GRAB_ORDER_LOCK + request.getId());
        try {
			if(!lock.tryLock()) {
				throw new StoneCustomerException("操作频繁，请刷新重试");
			}

			// 检查订单是否已被抢
			if (!DeliveryOrderStatusEnum.WAITING_FOR_ORDERS.getCode().equals(dbDeliveryOrder.getStatus())) {
				throw new StoneCustomerException(BasicResultCode.ORDER_IS_GRAP, "订单已被抢");
			}

			TravelingDistanceVo travelingDistanceVo = commonFeignApi.selectTravelingDistance(
					BigDecimal.valueOf(request.getRiderLng().doubleValue()),
					BigDecimal.valueOf(request.getRiderLat().doubleValue()),
					BigDecimal.valueOf(Double.parseDouble(dbDeliveryOrder.getStartLng())),
					BigDecimal.valueOf(Double.parseDouble(dbDeliveryOrder.getStartLat()))
			).getData();

			// 获取全国配送区域配置
			// TODO - 按当前城市地区计算
			TbDeliveryAreaConfig nationalDeliveryAreaConfig = deliveryAreaConfigService.getById(BusinessType.DELIVERY_AREA_CONFIG_NATIONAL_ID);
			if(nationalDeliveryAreaConfig == null){
				throw new StoneCustomerException("全国配送区域配置获取失败");
			}

            if(travelingDistanceVo.getDistanceValue().compareTo(nationalDeliveryAreaConfig.getNearbyRidersDistanceLimit()) > 0) {
            	log.info("抢单失败，当前已超出范围,distanceValue={0},nearbyRidersDistanceLimit={1}",travelingDistanceVo.getDistanceValue(),nationalDeliveryAreaConfig.getNearbyRidersDistanceLimit());
                throw new StoneCustomerException("抢单失败，当前已超出范围");
            }

			TbRiderLevel tbRiderLevel = tbRiderLevelMapper.selectById(rider.getLevelId());
			if(ObjectUtils.isEmpty(tbRiderLevel)){
				throw new StoneCustomerException("骑手等级异常");
			}

            // 计算骑手实际收入、平台实际收入
			BigDecimal courierIncome = BigDecimal.ZERO;
			BigDecimal platformIncome = BigDecimal.ZERO;
			if(tbRiderLevel.getSettlementMode() == Quantity.INT_1){
				// 按固定金额分成
				courierIncome = tbRiderLevel.getPerOrderFixedAmount().compareTo(dbDeliveryOrder.getDeliveryFee()) <= 0
						? tbRiderLevel.getPerOrderFixedAmount()
						: dbDeliveryOrder.getDeliveryFee();
			}else if(tbRiderLevel.getSettlementMode() == Quantity.INT_2){
				// 按比例分成
				BigDecimal deliveryFeeRatio = tbRiderLevel.getDeliveryFeeRatio().divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
				courierIncome = dbDeliveryOrder.getDeliveryFee().multiply(deliveryFeeRatio);
			}else{
				throw new StoneCustomerException("骑手等级配置有误");
			}
			platformIncome = dbDeliveryOrder.getDeliveryFee().subtract(courierIncome);

				// todo - 分钟用int标识，导致时间不准
			TbDeliveryOrder updateDeliveryOrder = new TbDeliveryOrder();
            updateDeliveryOrder.setId(dbDeliveryOrder.getId());
			updateDeliveryOrder.setArrivalMinute(travelingDistanceVo.getDurationValue().divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_HALF_UP).intValue());
			updateDeliveryOrder.setStatus(DeliveryOrderStatusEnum.WAITING_TO_ARRIVE.getCode());
			updateDeliveryOrder.setRiderId(rider.getId());
			updateDeliveryOrder.setRiderName(rider.getRealName());
			updateDeliveryOrder.setAcceptTime(new Date());
			updateDeliveryOrder.setCourierIncome(courierIncome);
			updateDeliveryOrder.setPlatformIncome(platformIncome);
			tbDeliveryOrderMapper.updateById(updateDeliveryOrder);

			// 移除redis里面的待抢单数据
			redisTemplate.opsForGeo().remove(ORDER_START_ADDRESS_KEY, dbDeliveryOrder.getId().toString());

			// 修改订单相关信息
			OrderParam updateOrder = new OrderParam();
			updateOrder.setId(dbDeliveryOrder.getOriginOrderId());
			updateOrder.setRiderId(updateDeliveryOrder.getRiderId());
			updateOrder.setRiderName(updateDeliveryOrder.getRiderName());
			updateOrder.setRiderMobile(rider.getMobile());
			orderFeignApi.updateRiderInfo(updateOrder);

		} catch (StoneCustomerException e) {
			throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
			lock.unlock();
		}
    }

	@Override
	public Page<TbDeliveryOrderResult> pageRiderOrder(TbDeliveryOrderParam.RiderOrderPageRequest param) {
		TbRider rider = riderSessionManager.getSession(TokenUtil.getToken());

		TbDeliveryOrderParam tbDeliveryOrderParam = new TbDeliveryOrderParam();
		tbDeliveryOrderParam.setRiderId(rider.getId());
		tbDeliveryOrderParam.setStatus(param.getStatus());
		tbDeliveryOrderParam.setQueryDate(param.getQueryDate());
		Page<TbDeliveryOrder> page = tbDeliveryOrderMapper.page(new Page<>(param.getPageNo(), param.getPageSize()), tbDeliveryOrderParam);

		Page<TbDeliveryOrderResult> pageResult = new Page<>();
		BeanUtils.copyProperties(page, pageResult);

		List<TbDeliveryOrderResult> resultList = new ArrayList<>();
		for (TbDeliveryOrder deliveryOrder : page.getRecords()) {
			TbDeliveryOrderResult tbDeliveryOrderResult = new TbDeliveryOrderResult();
			BeanUtils.copyProperties(deliveryOrder, tbDeliveryOrderResult);
			resultList.add(tbDeliveryOrderResult);
		}

		// 填充预计到店分钟等字段值
		if(param.getRiderLng() != null && param.getRiderLat() != null){
			resultList.forEach(result -> {
				setDistanceField(result, param.getRiderLng(), param.getRiderLat());
			});
		}

		pageResult.setRecords(resultList);

		return pageResult;
	}

	@Override
	public void transferOrder(TbDeliveryOrderParam param) {
		TbRider tbRider = riderSessionManager.getSession(TokenUtil.getToken());

		// 获取订单信息
		TbDeliveryOrder dbDeliveryOrder = tbDeliveryOrderMapper.selectById(param.getId());
		if(ObjectUtils.isEmpty(dbDeliveryOrder)) {
			throw new StoneCustomerException("配送订单不存在");
		}

		TbRiderLevel tbRiderLevel = tbRiderLevelMapper.selectById(tbRider.getLevelId());
		if(ObjectUtils.isEmpty(tbRiderLevel)){
			throw new StoneCustomerException("骑手等级异常");
		}

		// 获取骑手的转单限制-单日
		String key = TRANSFER_ORDER_LIMIT_KEY + DateUtilsPlus.formatDate(new Date(), "YYYYMMdd") + tbRider.getId();
		if(!redisUtils.hasKey(key)){
			// key不存在，初始化
			redisUtils.set(key, Convert.toStr(tbRiderLevel.getTransferLimit()));
		}

		int transferNum = Convert.toInt(redisUtils.get(key));
		if(transferNum == 0) {
			throw new StoneCustomerException(BasicResultCode.ORDER_TRANSFER_EXCEED_LIMIT, "转单次数已达到上限");
		}

		// 只允许待到店状态转单
		if(!DeliveryOrderStatusEnum.WAITING_TO_ARRIVE.getCode().equals(dbDeliveryOrder.getStatus())
				&& !DeliveryOrderStatusEnum.WAITING_FOR_PICKUP.getCode().equals(dbDeliveryOrder.getStatus())) {
			throw new StoneCustomerException("当前订单状态不允许转单");
		}

		// 更新订单信息，待接单，重新分配
		TbDeliveryOrder updateOrder = new TbDeliveryOrder();
		updateOrder.setId(dbDeliveryOrder.getId());
		updateOrder.setStatus(DeliveryOrderStatusEnum.WAITING_FOR_ORDERS.getCode());
		updateOrder.setIsTransfer(true);
		updateOrder.setTransferTime(new Date());
		int count = tbDeliveryOrderMapper.updateById(updateOrder);
		if(count > 0) {
			// 可转单次数减1
			redisUtils.set(key, Convert.toStr(transferNum - 1));

			// 记录配送订单出发地位置到Redis中
			Point merPoint = new Point(Convert.toDouble(dbDeliveryOrder.getStartLng()), Convert.toDouble(dbDeliveryOrder.getStartLat()));
			redisTemplate.opsForGeo().add(ORDER_START_ADDRESS_KEY, merPoint, dbDeliveryOrder.getId().toString());
		}else {
			throw new StoneCustomerException("转单失败，订单更新异常");
		}
	}

	@Override
	public TbDeliveryOrderResult orderDetail(TbDeliveryOrderParam param) {
		TbRider rider = riderSessionManager.getSession(TokenUtil.getToken());

		TbDeliveryOrder deliveryOrder = tbDeliveryOrderMapper.selectById(param.getId());

		TbDeliveryOrderResult result = new TbDeliveryOrderResult();
		BeanUtils.copyProperties(deliveryOrder, result);

		// 填充预计到店分钟等字段值
		if(param.getRiderLng() != null && param.getRiderLat() != null){
			setDistanceField(result, param.getRiderLng(), param.getRiderLat());
		}

		return result;
	}

	/**
	 * 填充预计到店分钟等字段值
	 * @param result
	 * @param riderLng
	 * @param riderLat
	 */
	private void setDistanceField(TbDeliveryOrderResult result, BigDecimal riderLng, BigDecimal riderLat) {
		try{
			TravelingDistanceVo travelingDistanceVo = commonFeignApi.selectTravelingDistance(
					BigDecimal.valueOf(riderLng.doubleValue()),
					BigDecimal.valueOf(riderLat.doubleValue()),
					BigDecimal.valueOf(Double.parseDouble(result.getStartLng())),
					BigDecimal.valueOf(Double.parseDouble(result.getStartLat()))
			).getData();

			// 预计到店分钟
			result.setArrivalMinute(travelingDistanceVo.getDurationValue().divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_HALF_UP).intValue());

			// 预计xx前送达
			int totalMinute = result.getArrivalMinute() + result.getDeliveryMinute();
			Date date = DateUtilsPlus.addMinutes(new Date(), totalMinute);
			String expectedCompleteTimeText = DateUtilsPlus.formatDate(date, "HH:mm");
			result.setExpectedCompleteTimeText(expectedCompleteTimeText);

			// 骑手位置到店铺地址距离公里数
			result.setShopDistance(travelingDistanceVo.getDistanceValue());
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	@Override
	public Map selectAllTabWaitHandleNum(TbDeliveryOrderParam param) {
		Map dataMap = new HashMap();

		//待配送订单
		LambdaQueryWrapper<TbDeliveryOrder> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(TbDeliveryOrder::getStatus, DeliveryOrderStatusEnum.WAITING_FOR_ORDERS.getCode());
		int waitDeliveryNum = tbDeliveryOrderMapper.selectCount(queryWrapper);
		dataMap.put("waitDeliveryNum", waitDeliveryNum);

		//配送中订单
		queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(TbDeliveryOrder::getStatus, DeliveryOrderStatusEnum.WAITING_TO_ARRIVE.getCode(),
				DeliveryOrderStatusEnum.WAITING_FOR_PICKUP.getCode(),
				DeliveryOrderStatusEnum.IN_DELIVERY.getCode());
		int deliveredNum = tbDeliveryOrderMapper.selectCount(queryWrapper);
		dataMap.put("deliveredNum", deliveredNum);
		return dataMap;
	}

	@Override
	public Map statistic(TbDeliveryOrderParam param) throws ParseException {
		Map resultMap = new HashMap();

		//只统计状态为[5=已完成]的订单数据

		//日期、订单数量、订单金额

		//1、查询开始日期(系统/订单服务第一次上线日期) - 今天
		/*String startDate = "2020-05-10";*/
		String startDate = tbDeliveryOrderMapper.selectStartDateOrder(null);
		if(startDate == null){
			startDate = DateUtilsPlus.formatDate(new Date(), "YYYY-MM-dd");
		}
		String endDate = DateUtilsPlus.formatDate(new Date(), "YYYY-MM-dd");
		List<String> betweenDays = DateUtilsPlus.getBetweenDays(startDate, endDate);

		//2、构造日期列表
		Map<String, Map> filterMap = new HashMap();
		List<Map<String, Object>> resultList = new ArrayList();
		for (String dateStr : betweenDays) {
			Map<String, Object> map = new HashMap<>();
			map.put("date", dateStr); //前端的变量名为date
			map.put("orderCount", 0);
			map.put("orderAmount", 0);
			resultList.add(map);
			//记录日期对应的集合元素，便于后续赋值
			filterMap.put(dateStr, map);
		}

		//3、查询每一个日期对应的 订单数量、订单金额
		List<Map<String, Object>> statisticList = tbDeliveryOrderMapper.selectStatisticOrder(null);
		statisticList.forEach(statisticMap -> {
			if(filterMap.containsKey(statisticMap.get("orderDate"))){
				//修改订单数据
				Map map = filterMap.get(statisticMap.get("orderDate"));
				map.put("orderCount", statisticMap.get("orderCount"));
				map.put("orderAmount", statisticMap.get("orderAmount"));
			}
		});

		resultMap.put("resultList", resultList);


		//订单表筛选条件-所有商家
		TbDeliveryOrderParam orderParam = new TbDeliveryOrderParam();

		//本月订单总数、上月订单总数、同比情况
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfMonth());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfMonth());
		int thisMonthCountPaid = tbDeliveryOrderMapper.selectCountCompleted(orderParam);

		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfLastMonth());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfLastMonth());
		int lastMonthCountPaid = tbDeliveryOrderMapper.selectCountCompleted(orderParam);

		//本周订单总数、上周订单总数、同比情况
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfWeek());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfWeek());
		int thisWeekCountPaid = tbDeliveryOrderMapper.selectCountCompleted(orderParam);
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfLastWeek());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfLastWeek());
		int lastWeekCountPaid = tbDeliveryOrderMapper.selectCountCompleted(orderParam);

		//本月销售总额、上月销售总额、同比情况
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfMonth());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfMonth());
		BigDecimal thisMonthSumActualPrice = tbDeliveryOrderMapper.selectSumActualPrice(orderParam);
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfLastMonth());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfLastMonth());
		BigDecimal lastMonthSumActualPrice = tbDeliveryOrderMapper.selectSumActualPrice(orderParam);

		//本周销售总额、上周销售总额、同比情况
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfWeek());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfWeek());
		BigDecimal thisWeekSumActualPrice = tbDeliveryOrderMapper.selectSumActualPrice(orderParam);
		orderParam.setStartTime(DateUtilsExtend.getBeginDayOfLastWeek());
		orderParam.setEndTime(DateUtilsExtend.getEndDayOfLastWeek());
		BigDecimal lastWeekSumActualPrice = tbDeliveryOrderMapper.selectSumActualPrice(orderParam);

		resultMap.put("thisMonthCountPaid", thisMonthCountPaid);
		resultMap.put("lastMonthCountPaid", lastMonthCountPaid);
		resultMap.put("thisWeekCountPaid", thisWeekCountPaid);
		resultMap.put("lastWeekCountPaid", lastWeekCountPaid);
		resultMap.put("thisMonthSumActualPrice", thisMonthSumActualPrice);
		resultMap.put("lastMonthSumActualPrice", lastMonthSumActualPrice);
		resultMap.put("thisWeekSumActualPrice", thisWeekSumActualPrice);
		resultMap.put("lastWeekSumActualPrice", lastWeekSumActualPrice);
		return resultMap;
	}

	@Override
	public void updateStatus(TbDeliveryOrderParam param) {
		//获取当前登录用户绑定的门店编号
		if(param.getFlag()!= Quantity.INT_1){
			throw new StoneCustomerException("标识错误");
		}

		TbDeliveryOrder dbOrder = this.getById(param.getId());
		if(dbOrder == null){
			throw new StoneCustomerException("该订单不存在");
		}

		// todo - copay 配送订单完成通用代码

//		//获取该订单的对应用户
//		Member orderMember = memberFeignApi.selectByPrimaryKey(dbOrder.getMemberId()).getData();
//
//		int status = 0;
//		switch (param.getFlag()){
//			//处理订单
//			case Quantity.INT_1:
//				if(dbOrder.getStatus() != Quantity.INT_2){
//					throw new StoneCustomerException("该订单状态非待处理，不允许修改");
//				}
//				//自取订单，将状态改为3=待自取(已处理)；配送订单，将状态改为4=待配送(已处理)
//				if(dbOrder.getShoppingWay() == Quantity.INT_1){
//					status = Quantity.INT_3;
//				}else if(dbOrder.getShoppingWay() == Quantity.INT_2){
//					status = Quantity.INT_4;
//				}
//				break;
//
//			//标记完成(自取订单)
//			case Quantity.INT_2:
//				if(dbOrder.getStatus() != Quantity.INT_3){
//					throw new StoneCustomerException("该订单状态非待自取，不允许修改");
//				}
//				//将状态改为6=已完成
//				status = Quantity.INT_6;
//				break;
//
//			//标记配送
//			case Quantity.INT_3:
//				if(dbOrder.getStatus() != Quantity.INT_4){
//					throw new StoneCustomerException("该订单状态非待配送，不允许修改");
//				}
//				//将状态改为5=已配送
//				status = Quantity.INT_5;
//				break;
//
//			//标记完成(配送订单)
//			case Quantity.INT_4:
//				if(dbOrder.getStatus() != Quantity.INT_5){
//					throw new StoneCustomerException("该订单状态非已配送，不允许修改");
//				}
//				//将状态改为6=已完成
//				status = Quantity.INT_6;
//				break;
//		}
//
//		// 更新Order数据
//		TbDeliveryOrder updateOrder = new TbDeliveryOrder();
//		updateOrder.setId(dbOrder.getId());
//		updateOrder.setStatus(status);
//		if(status == Quantity.INT_6){
//			updateOrder.setOrderCompletionTime(new Date());
//		}
//		this.updateById(updateOrder);
//
//		//发送短信提醒自提
//		if(status==Quantity.INT_3){
//			// 发送短信提醒自提
//			aliyunSms.sendPickUpOrderCompleteMessage(dbOrder.getContactPhone(), String.valueOf(dbOrder.getQueueNo()), dbOrder.getShopName());
//			//发送微信服务通知
//			wxNotifyService.sendPickUpOrderCompleteMessage(orderMember.getOpenId(), String.valueOf(dbOrder.getQueueNo()), dbOrder.getShopName(), dbOrder.getShopAddress(), dbOrder.getDescription());
//
//		}else if(status==Quantity.INT_5){
//			// 发送短信提醒正在配送中
//			aliyunSms.sendTakeOutOrderDeliveryMessage(dbOrder.getContactPhone());
//			//发送微信服务通知
//			String addressStr = dbOrder.getContactProvince() + dbOrder.getContactCity() + dbOrder.getContactArea() + dbOrder.getContactStreet() + dbOrder.getContactHouseNumber();
//			wxNotifyService.sendTakeOutOrderDeliveryMessage(orderMember.getOpenId(), String.valueOf(dbOrder.getQueueNo()), dbOrder.getShopName(), addressStr, dbOrder.getDescription());
//		}
	}

	@Override
	public void refuse(TbDeliveryOrderParam param) {
		TbRider loginRider = riderSessionManager.getSession(TokenUtil.getToken());

		// 将拒绝的订单存到缓存里
		Map refuseMap = redisUtils.hasKey(RedisConstant.REFUSE_ORDER_KEY) ? JSON.parseObject((String) redisUtils.get(RedisConstant.REFUSE_ORDER_KEY), HashMap.class) : new HashMap();
		List<Long> orderIdList = refuseMap.containsKey(loginRider.getId()) ? (List) refuseMap.get(loginRider.getId()) : new ArrayList<>();
		orderIdList.add(param.getId());
		refuseMap.put(loginRider.getId(), orderIdList);
		redisUtils.set(RedisConstant.REFUSE_ORDER_KEY, JSON.toJSONString(refuseMap));
	}

	@Override
	public void confirmToStore(TbDeliveryOrderParam param) {
		TbDeliveryOrder dbDeliveryOrder = this.getById(param.getId());

		// 订单状态判断
		if(!DeliveryOrderStatusEnum.WAITING_TO_ARRIVE.getCode().equals(dbDeliveryOrder.getStatus())) {
			throw new StoneCustomerException("当前订单状态不允许进行该操作");
		}

		TbDeliveryOrder updateOrder = new TbDeliveryOrder();
		updateOrder.setId(dbDeliveryOrder.getId());
		updateOrder.setStatus(DeliveryOrderStatusEnum.WAITING_FOR_PICKUP.getCode());
		updateOrder.setArriveTime(new Date());
		updateOrder.setUpdateTime(new Date());
		this.updateById(updateOrder);
	}

	@Override
	public void confirmPickUp(TbDeliveryOrderParam param) {
		TbDeliveryOrder dbDeliveryOrder = this.getById(param.getId());

		// 订单状态判断
		if(!DeliveryOrderStatusEnum.WAITING_FOR_PICKUP.getCode().equals(dbDeliveryOrder.getStatus())) {
			throw new StoneCustomerException("当前订单状态不允许进行该操作");
		}

		TbDeliveryOrder updateOrder = new TbDeliveryOrder();
		updateOrder.setId(dbDeliveryOrder.getId());
		updateOrder.setStatus(DeliveryOrderStatusEnum.IN_DELIVERY.getCode());
		updateOrder.setPickImg(param.getPickImg());
		updateOrder.setDeliveryTime(new Date());
		updateOrder.setUpdateTime(new Date());
		this.updateById(updateOrder);

		// 骑手已取货时，同步修改原订单的状态为5=已配送
		orderFeignApi.confirmPickUp(dbDeliveryOrder.getOriginOrderId());
	}

	@Override
	public void confirmDelivery(TbDeliveryOrderParam param) {
		TbDeliveryOrder dbDeliveryOrder = this.getById(param.getId());

		// 订单状态判断
		if(!DeliveryOrderStatusEnum.IN_DELIVERY.getCode().equals(dbDeliveryOrder.getStatus())) {
			throw new StoneCustomerException("当前订单状态不允许进行该操作");
		}

		TbDeliveryOrder updateOrder = new TbDeliveryOrder();
		updateOrder.setId(dbDeliveryOrder.getId());
		updateOrder.setStatus(DeliveryOrderStatusEnum.COMPLETED.getCode());
		updateOrder.setEndImg(param.getEndImg());
		updateOrder.setCompleteTime(new Date());
		updateOrder.setUpdateTime(new Date());
		this.updateById(updateOrder);

		// 骑手配送完成时，同步修改原订单的状态为6=已完成
		orderFeignApi.confirmDelivery(dbDeliveryOrder.getOriginOrderId());
	}

	@Override
	public TbDeliveryOrder selectByOriginOrderId(int originOrderId) {
		LambdaQueryWrapper<TbDeliveryOrder> wrapper = new LambdaQueryWrapper();
		wrapper.eq(TbDeliveryOrder::getOriginOrderId, originOrderId);
		return this.getOne(wrapper);
	}
}